// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

// A server to receive EchoRequest and send back EchoResponse.

#include <gflags/gflags.h>
#include <butil/logging.h>
#include <brpc/server.h>
#include <json2pb/pb_to_json.h>
#include "echo.pb.h"
#include <opencv2/opencv.hpp>

DEFINE_bool(echo_attachment, true, "Echo attachment as well");
DEFINE_int32(port, 8000, "TCP Port of this server");
DEFINE_string(listen_addr, "", "Server listen address, may be IPV4/IPV6/UDS."
            " If this is set, the flag port will be ignored");
DEFINE_int32(idle_timeout_s, -1, "Connection will be closed if there is no "
             "read/write operations during the last `idle_timeout_s'");

// Your implementation of example::EchoService
// Notice that implementing brpc::Describable grants the ability to put
// additional information in /status.
namespace example {
class EchoServiceImpl : public EchoService {
public:
    EchoServiceImpl() {}
    virtual ~EchoServiceImpl() {}
    virtual void Echo(google::protobuf::RpcController* cntl_base,
                      const EchoRequest* request,
                      EchoResponse* response,
                      google::protobuf::Closure* done) {
        // 该对象有助于以 RAII 风格调用 done->Run()。如需要异步处理请求，可传递 done_guard.release()。
        brpc::ClosureGuard done_guard(done);

        brpc::Controller* cntl = static_cast<brpc::Controller*>(cntl_base);

        const ImageData& img_data = request->image();

        // 从二进制数据重建图像
        cv::Mat image(img_data.height(), img_data.width(), CV_8UC(img_data.channels()),
                     const_cast<void*>(static_cast<const void*>(img_data.data().data())));

        // 构建保存路径
        std::string save_path = request->image_name();

        // 保存图像
        bool success = cv::imwrite(save_path, image);

        response->set_success(success);

        if (success) {
            response->set_message("saved image to " + save_path + ".");
            LOG(INFO) << "Request[log_id=" << cntl->log_id() << "], Received and saved image from "
                      << cntl->remote_side() << " as " << save_path;
        } else {
            response->set_message("Failed to save image");
            LOG(ERROR) << "Failed to save received image";
        }
    }
};
}  // namespace example

// 与echo_c++服务端的main函数是相同的
int main(int argc, char* argv[]) {
    // 打印ProtoBuf版本，3.6.1和3.12.4是常用的稳定版本
    // std::cout << "Protocol Buffer 版本: " << GOOGLE_PROTOBUF_VERSION << std::endl;

    // 建议使用gflags解析参数
    GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);

    // 创建服务器实例
    brpc::Server server;

    // 创建服务实例
    example::EchoServiceImpl echo_service_impl;

    // 将服务实例添加到服务器中
    // 注意第二个参数, 因为服务实例在栈上创建, 所以不想让服务器删除它, 否则使用brpc::SERVER_OWNS_SERVICE
    if (server.AddService(&echo_service_impl, 
                          brpc::SERVER_DOESNT_OWN_SERVICE) != 0) {
        LOG(ERROR) << "Fail to add service";
        return -1;
    }

    butil::EndPoint point;
    if (!FLAGS_listen_addr.empty()) {
        if (butil::str2endpoint(FLAGS_listen_addr.c_str(), &point) < 0) {
            LOG(ERROR) << "Invalid listen address:" << FLAGS_listen_addr;
            return -1;
        }
    } else {
        point = butil::EndPoint(butil::IP_ANY, FLAGS_port);
    }

    // 启动服务器
    brpc::ServerOptions options;
    options.idle_timeout_sec = FLAGS_idle_timeout_s;
    if (server.Start(point, &options) != 0) {
        LOG(ERROR) << "Fail to start EchoServer";
        return -1;
    }

    // Wait until Ctrl-C is pressed, then Stop() and Join() the server.
    server.RunUntilAskedToQuit();
    return 0;
}
